import axios from 'axios'
import envConfig from '@/config'

const service = axios.create({
  baseURL: envConfig.baseApi,
})

service.interceptors.request.use(
  config => {
    config.headers.Authorization = 'Bearer ' + localStorage.getItem('token')
    return config
  },
  error => {
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  res => {
    if(res.data.code===200){
      return res.data
    }else{
      return Promise.reject(res.message)
    }
  },
  error => {
    return Promise.reject(error)
  },
)

export const request = (options) =>{
  options.method = options.method || 'get'
  //关于get请求参数调整
  if(options.method.toLowerCase()==='get'){
    options.params = options.data
  }
  //mock开关
  let isMock = envConfig.mock;
  if(typeof options.mock !== 'undefined'){
    isMock = options.mock
  }
  //针对环境做处理
  if(envConfig.env === 'prod'){
    service.defaults.baseURL = envConfig.baseApi
  }else{
    service.defaults.baseURL = isMock ? envConfig.mockApi : envConfig.baseApi
  }

  return service(options)
}
